package org.icnmasjid.member.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.PaymentCategory;
import org.icnmasjid.member.service.Manager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class PaymentCategoryFormController extends BaseFormController {
    public PaymentCategoryFormController() {
        setCommandName("paymentCategory");
        setCommandClass(PaymentCategory.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        PaymentCategory paymentCategory = null;

        if (!StringUtils.isEmpty(id)) {
            paymentCategory = (PaymentCategory) manager.getObject(PaymentCategory.class, new Integer(id));
        } else {
            paymentCategory = new PaymentCategory();
        }

        return paymentCategory;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        PaymentCategory paymentCategory = (PaymentCategory) command;
        boolean isNew = (paymentCategory.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            manager.removeObject(PaymentCategory.class, paymentCategory.getId());

            saveMessage(request, getText("paymentCategory.deleted", locale));
        } else {
            manager.saveObject(paymentCategory);

            String key = (isNew) ? "paymentCategory.added" : "paymentCategory.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editPaymentCategory.html", "id", paymentCategory.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
